using System.Drawing.Imaging;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.AspNetZeroCore.Net;
using Abp.Authorization;
using Abp.Extensions;
using Abp.IO.Extensions;
using Abp.Runtime.Session;
using Abp.UI;
using Abp.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Magicodes.Admin.Authorization;
using Magicodes.Admin.MultiTenancy;
using Magicodes.Admin.Storage;
using Magicodes.Admin.Web.Helpers;
using System.IO;
using System.Net.Http.Headers;
using Magicodes.Admin.WULINGAddresss;
using Magicodes.Admin.WULINGAddresss.Dto;
using System.Collections.Generic;

namespace Magicodes.Admin.Web.Controllers
{
    [AbpMvcAuthorize]
    public class WULINGAddressController : AdminControllerBase
    {
        private readonly IWULINGAddressAppService  _wULINGAddressAppService;

        public WULINGAddressController(IWULINGAddressAppService  wULINGAddressAppService)
        {
            _wULINGAddressAppService = wULINGAddressAppService;
        }

        [HttpPost]
        [AbpMvcAuthorize(AppPermissions.Pages_Manager_WulingAddressLibrary)]
        public async Task<JsonResult> ImportFromExcel()
        {
            try
            {
                var importFile = Request.Form.Files.First();

                //Check input
                if (importFile == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                if (importFile.Length > 30720 * 1000) //30KB*1000
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                byte[] fileBytes;
                using (var stream = importFile.OpenReadStream())
                { 

                    var data = ExcelHelper.ExcelReader(stream);
                    var columns = new List<string> {
                        "ServiceStationCode",
                        "ServiceStationName",
                        "PostCode",
                        "Contact",
                        "ContactPhoneNumber",
                        "ReceiverAddress",
                        "ServiceStationManager",
                        "ServiceStationManagerPhoneNumber",
                        "Area",
                        "Province",
                        "City",
                        "District",
                    };
                    data.Tables[0].Rows.RemoveAt(0);
                    var importList = data.Tables[0].ExcelReaderToEntitys<ImportAddressInputDto>(columns);

                   await _wULINGAddressAppService.ImportFromExcel(importList.ToList());

                    return Json(new AjaxResponse(new { code = 0, msg = "" }));
                }


            }
            catch (UserFriendlyException ex)
            {
                return Json(new AjaxResponse(new ErrorInfo(ex.Message)));
            }
        }




    }
}